<template>
  <el-upload
    class="avatar-uploader"
    action="/meter/user/logo"
    :show-file-list="false"
    :headers="{'x-Token':token}"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload">
    <img v-if="logo" :src="logo" class="avatar">
    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
  </el-upload>
</template>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<script>
import {getToken} from "@/utils/auth";

export default {
  data() {
    return {
      fileTypes:['image/jpeg','image/png'],
      token:''
    }
  },
  props: {
    logo: {
      type: String,
      default: ''
    }
  },
  created() {
    this.token = getToken()
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.logo = URL.createObjectURL(file.raw)
      this.$message.success('LOGO设置成功')
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 <= 1;

      if (this.fileTypes.indexOf(file.type) == -1){
        this.$message.error('只允许导入png/jpg/jpeg文件');
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 1MB!');
        return false
      }
      return true;
    }
  }
}
</script>
